package model

import (
	"ginblog/tools/pagination"
	"ginblog/utils/errmsg"
)

type Article struct {
	BaseModel
	Category    Category `gorm:"FOREIGNKEY:CId"`
	ArticleName string   `gorm:"type:varchar(20);not null;comment:'文章名称'" json:"article_name"`
	Desc        string   `gorm:"type:varchar(32);not null;comment:'简介'" json:"desc"`
	CId         int      `gorm:"type:int(11);default 0;comment:'分类ID'" json:"c_id"`
	Content     string   `gorm:"type:text(512);comment:'内容'" json:"content"`
	ArtIcon     string   `gorm:"type:text(512);comment:'文章图标'" json:"art_icon"`
	IsRecommend string   `gorm:"type:int(2);comment:'是否推荐位,0:不推荐，1:推荐;default 0;'" json:"is_recommend"`
}

// SelectAllArt /查询所有文章
func (a *Article) SelectAllArt(page *pagination.Pagination) {
	var articleList []Article
	err := Db.Preload("Category").Limit(page.GetPageSize()).Offset(page.GetOffset()).Find(&articleList).Count(&page.Total).Error
	if err != nil {
		a.SteCodeMsg(errmsg.ERROR)
	}
	page.SetTotalPage()
	page.Data = articleList
}

// SelectCatArt /查询对应分类下的所有文章
func (a *Article) SelectCatArt(page *pagination.Pagination) {
	var articleList []Article
	err := Db.Preload("Category").Where(a).Limit(page.GetPageSize()).Offset(page.GetOffset()).Find(&articleList).Count(&page.Total).Error
	if err != nil {
		a.SteCodeMsg(errmsg.ERROR)
	}
	page.SetTotalPage()
	page.Data = articleList
}

// SelectAllArtRec /查询推荐所有文章
func (a *Article) SelectAllArtRec(page *pagination.Pagination) {
	var articleList []Article
	err := Db.Preload("Category").Where("is_recommend = ?", 1).Limit(page.GetPageSize()).Offset(page.GetOffset()).Find(&articleList).Count(&page.Total).Error
	if err != nil {
		a.SteCodeMsg(errmsg.ERROR)
	}
	page.SetTotalPage()
	page.Data = articleList
}

// AddArt /新增文章
func (a *Article) AddArt() bool {
	err := Db.Create(&a).Error
	if err != nil {
		return false
	}
	return true
}

// EditArt /编辑分类
func (a *Article) EditArt() bool {
	err := Db.Model(&a).Where("id = ? ", a.ID).Omit("Id").Updates(a).Error
	if err != nil {
		return false
	}
	return true
}

// DelArt /删除分类
func (a *Article) DelArt() bool {
	err := Db.Delete(&Article{}, a.ID).Error
	if err != nil {
		return false
	}
	return true
}
